<template>
    <TransitionGroup class="drag-sort-box" name="sort" tag="div">
        <div class="drag-sort-item" draggable="true" v-for="(item, index) in images" :key="item"
            @dragstart="dragstart(item, index)" @dragenter="dragenter(item, $event)" @dragend="dragend(item, $event)"
            @dragover="dragover($event)">
            <p class="moxsind">{{ index + 1 }}</p>
            <img :src="item" :class="index == dargIndex ? 'active' : ''" />
        </div>
    </TransitionGroup>
</template>

<script setup lang="ts">
import { ref, defineProps } from 'vue';


const props: any = defineProps({
    imageList: {
        type: Array,
        defalut: () => []
    },
    sortType: {
        type: String,
        defalut: 'insert'
    }
});

const images = ref([...props.imageList]);  // 图片列表
const dargIndex = ref(-1);  // 拖拽图片下标

let oldData: any = null;
let newData: any = null;

const dragstart = (value: String, index: number) => {
    oldData = value;
    dargIndex.value = index
}

const dragenter = (value: String, e: any) => {
    newData = value;
    e.preventDefault();
}

const dragover = (e: any) => {
    e.preventDefault();
}

const dragend = (value: any, e: any) => {
    if (oldData !== newData) {
        let oldIndex = images.value.indexOf(oldData); // 寻找旧的下标
        let newIndex = images.value.indexOf(newData);

        if (props.sortType == 'insert') {
            let newItems = [...images.value];
            newItems.splice(oldIndex, 1);
            newItems.splice(newIndex, 0, oldData);
            images.value = [...newItems];
        } else {
            [images.value[oldIndex], images.value[newIndex]] = [images.value[newIndex], images.value[oldIndex]]
        }
    }
    dargIndex.value = -1;
}

</script>

<style scoped>
* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    line-height: 1;
}

.drag-sort-box {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
}

.drag-sort-box .drag-sort-item {
    width: 100px;
    height: 100px;
    margin: 2px;
    cursor: pointer;
    transition: all 0.3s;
    background: #ccc;
    position: relative;
}

.drag-sort-box .drag-sort-item img {
    width: 100%;
    height: 100%;
    transition: all 0.3s;
    position: relative;
}

.drag-sort-box .drag-sort-item .active {
    border-radius: 30px;
    box-shadow: 0 0 15px rgba(0, 0, 0, 0.3);
    opacity: 0;
}

.moxsind {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #dfd6d6;
    text-shadow: 0 0 15px rgba(0, 0, 0, 0.3);
    font-size: 50px;
    font-weight: 600;
    position: absolute;
    top: 0;
    left: 0;
}
</style>
